public class HIndex {

    public int hIndex(int[] citations) {
        int n = citations.length;
        int l = 0;
        int r = citations.length - 1;
        int ans = Integer.MIN_VALUE;
        while (l < r) {
            int mid = l + (r - l) / 2;
            if (citations[mid] > n - mid) {
                r = mid;
            } else if (citations[mid] == n - mid) {
                ans = Math.max(ans, n - mid);
                l = mid + 1;
            } else {
                l = mid + 1;
            }
        }
        return ans == Integer.MIN_VALUE ? citations[l] == 0 ? 0 : n - l : ans;
    }
}
